<template>
  <el-row type="flex" justify="center" align="middle" class="entryPage">
    <el-form ref="form" label-width="80px">
      <h2>登录</h2>
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="密码">
        <el-input
          v-model="form.password"
          type="password"
          @keyup.enter.native="onSubmit"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          @keyup.enter.native="onSubmit"
          >提交</el-button
        >
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    onSubmit() {
      // 预先校验一下用户是否输入为空
      if (this.form.username == "" || this.form.password == "") {
        this.$message.warning("请输入用户名和密码");
        return;
      }
      // 发送请求获取登录信息
      this.$axios({
        method: "post",
        url: "/login",
        data: this.form,
      }).then((res) => {
        console.log(res.data);
        // 登录成功储存token
        if (res.data.message == "登录成功") {
          localStorage.setItem("token", res.data.data.token);
          localStorage.setItem("userId", res.data.data.user.id);
          this.$message.success("登录成功");
          this.$router.push("/postlist");
        } else {
          this.$message.error("用户密码错误");
        }
      });
    },
    reset() {
      this.form = {
        username: "",
        password: "",
      };
    },
  },
};
</script>

<style lang="less" scoped>
.entryPage {
  min-height: 100vh;
  background-color: #e4e4e4;
  background: url("../images/bg-banner.jpg") no-repeat;
  h2 {
    padding-left: 150px;
    padding-bottom: 20px;
    color: #66b1ff;
  }
}
</style>